package com.example.recyclerviewdemo.listview;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.recyclerviewdemo.R;

import java.util.List;

/**
 * @author wdl
 */
public class FruitAdapter extends ArrayAdapter<Fruit> implements View.OnClickListener {
    private int resourceId;

    public FruitAdapter(Context context, int resourceId, List<Fruit> objects) {
        super(context, resourceId, objects);
        this.resourceId = resourceId;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //获取当前的Fruit实例
        Fruit fruit = getItem(position);
/*
View view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
ImageView imageView = view.findViewById(R.id.iv_fruit_image);
TextView textView = view.findViewById(R.id.tv_fruit_name);
imageView.setImageResource(fruit.getImageId());
textView.setText(fruit.getName());
return view;
性能优化1:通过convertView这个参数对于将之前加载好的布局进行了缓存
性能优化2：通过ViewHolder避免每次View都要重新去findViewById()
*/

        View view;
        ViewHolder viewHolder;
        if (convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);

            viewHolder = new ViewHolder();
            viewHolder.fruitImage = view.findViewById(R.id.iv_fruit_image);
            viewHolder.fruitName = view.findViewById(R.id.tv_fruit_name);
            //将ViewHolder存储在View中
            view.setTag(viewHolder);
        } else {
            view = convertView;
            //重新获取ViewHolder
            viewHolder = (ViewHolder) view.getTag();
        }

        viewHolder.fruitImage.setImageResource(fruit.getImageId());
        viewHolder.fruitName.setText(fruit.getName());
        viewHolder.fruitImage.setOnClickListener(this);
        viewHolder.fruitName.setOnClickListener(this);

        return view;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_fruit_image:
                Toast.makeText(getContext(), "点击了水果", Toast.LENGTH_LONG).show();
                break;
            case R.id.tv_fruit_name:
                Toast.makeText(getContext(), "点击了文字", Toast.LENGTH_LONG).show();
                break;
            default:
        }
    }

    private class ViewHolder {
        ImageView fruitImage;
        TextView fruitName;
    }
}


